package com.zhida.common.config;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhida.common.interceptor.TokenInterceptor;
import com.zhida.common.interceptor.UserInfoInterceptor;
import com.zhida.common.mapper.RolePermissionMapper;
import com.zhida.common.utils.ObjectUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.*;

import static com.zhida.common.utils.StaticKeyUtil.USER_ROLE_KEY;

/**
 * Create by zhh 2024/7/5 1:25
 */
@Slf4j
@Configuration
@ConditionalOnClass(DispatcherServlet.class)
public class MvcConfig implements WebMvcConfigurer {

    @Bean
    public UserInfoInterceptor getUserInfoInterceptor(){
        return new UserInfoInterceptor();
    }
    @Bean
    public TokenInterceptor getTokeninterceptor(){
        return new TokenInterceptor();
    }

    @Resource
    RedisTemplate<String,String> redisTemplate;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 不拦截
        List<String> excludePath = null;
        try {
            excludePath = getExcludePathList();
            System.out.println(Arrays.toString(excludePath.toArray()));
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        log.info("启动拦截器");
        // 注册拦截器
        //        token interceptor
        registry.addInterceptor(getTokeninterceptor()).excludePathPatterns(excludePath).order(1);
        //        user interceptor
        registry.addInterceptor(getUserInfoInterceptor()).excludePathPatterns(excludePath).order(2);

    }

    //  辅助功能：根据权限表，动态创建拦截器
    public List<String> getExcludePathList() throws JsonProcessingException {
        //  从数据库中读取权限规则
//        reloadRole();
        List<String> excludePath = new ArrayList<>();
        String roleJson = redisTemplate.opsForValue().get(USER_ROLE_KEY);
        if (StringUtils.isNotBlank(roleJson)){
            ObjectMapper mapper = new ObjectMapper();
            try {
                List<Map<String, String>> maps = mapper.readValue(roleJson, new TypeReference<List<Map<String, String>>>() {});

                for (Map<String, String> map : maps) {
                    // 100为公开接口，不拦截
                    if (map.get("permission_level").equals("100")){
                        excludePath.add(map.get("URI") + "/**");
                    }
                }

            }catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }else {
            log.error("用户权限数据读取失败，请重启该服务。");
        }
        return excludePath;
    }
}
